using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Input.Touch;
using System.Threading;
using System.IO.IsolatedStorage;
using System.IO;
using System.Text;
using ebookreader.Resources;

namespace ebookreader
{
  public class ReaderState
  {
    // current book, current font, current page, ...
    public int CurrentPage { get; set; }
  }

    

  public class Reader : Menu
  {

      public struct Page
      {
          public int firstWord;
          public int numWords;
          public System.Text.StringBuilder text;
      }


    #region Fields

    static readonly int MARGIN = 5;

    //GraphicsDeviceManager graphics;
    //public IInputManager input_manager;
    SpriteFont font;
    //SpriteBatch sprite_batch;
    Vector2 position = new Vector2(MARGIN, MARGIN);
    List<string> words;

    public static List<Page> pages;
    public static List<Page> pages_portrait = new List<Page>();
    public static List<Page> pages_landscape = new List<Page>();
    Color textColor;
    Color bgColor;
    float scale;
    string book_path;
    public int current_page = 0;
    string fontident;
    public State currentState;


    float timetoload = 0;
    #endregion

    public Reader(Game game, SpriteFont font, Book book)
      : base(game)
    {
      //this.font = font;
      //if (font == null)
      //{
          //SavedOptions so = OptionsMenu.GetSavedOptions();

      //}
          this.book_path = book.filename;
          this.scale = 1;
          this.bgColor = Color.Black;
          this.textColor = Color.Black;
          this.scale = 1;
          
      UpdateOrder = (int)ScreenOrder.Reader;
      DrawOrder = (int)ScreenOrder.Reader;

      currentState = Game.Services.GetService(typeof(State)) as State;
      currentState.currentBook = book;

      game.Exiting += new EventHandler<EventArgs>((a, b) => 
      { currentState.currentBook.currentWord = pages[current_page].firstWord; currentState.SaveState(); });
    }

    //SavedOptions so;
    public Reader(Game game, Book book)
        : this(game, null, book )
    {
    }


    public override void Initialize()
    {
        //Game.Components.Add(new InputManager(Game));
        currentState = Game.Services.GetService(typeof(State)) as State;
        sprite_batch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;

        this.font = Game.Content.Load<SpriteFont>("Fonts/Usable/" + OptionMenu.fonts[currentState.options.font] + OptionMenu.sizes[currentState.options.size]);
        fontident = OptionMenu.fonts[currentState.options.font] + OptionMenu.sizes[currentState.options.size];
        //input_manager = new InputManager(Game);
        //Game.Components.Add(input_manager as IGameComponent);
        //graphics = Game.Services.GetService(typeof(GraphicsDeviceManager)) as GraphicsDeviceManager;
        input_manager.OnTap += new InputManager.Tap(OnTap);
        input_manager.onBackButtonPressed += new InputManager.Back(() => {
            Game.TargetElapsedTime = TimeSpan.FromSeconds(1 / 30f); 
            ScreenManager.SelectMainMenu(Game);
            Game.TargetElapsedTime = TimeSpan.FromSeconds(1 / 30f);
        });

        Game.Window.OrientationChanged += new EventHandler<EventArgs>(Window_OrientationChanged);

        base.Initialize();
    }

    void Window_OrientationChanged(object sender, EventArgs e)
    {
        switch (Game.Window.CurrentOrientation)
        {
            case DisplayOrientation.LandscapeLeft:
                if (pages.Count > 0)
                {
                    if (!page_not_loaded)
                    {
                        var current_word = pages[current_page].firstWord;
                        pages = pages_landscape;
                        current_page = findPage(current_word);
                    }
                    else
                        pages = pages_landscape;

                }
                else
                    pages = pages_landscape;
                break;
            case DisplayOrientation.Portrait:
                if (pages.Count > 0)
                {
                    if (!page_not_loaded)
                    {
                        var current_word = pages[current_page].firstWord;
                        pages = pages_portrait;
                        current_page = findPage(current_word);
                    }
                    else
                        pages = pages_portrait;

                }
                else
                    pages = pages_portrait;
                break;
        }

        
    }
      
    Texture2D background, bookbody, menu, loading_back, loading_icon;
    SpriteFont font_button;
    BoxedLabelButton menu_button;
    SoundEffect page_flip;
    static string prev_book_path = "";
    static string prev_font = "";
    protected override void LoadContent()
    {
        background = Game.Content.Load<Texture2D>("Definitivo/background");
        bookbody = Game.Content.Load<Texture2D>("todo/white");
        menu = Game.Content.Load<Texture2D>("Definitivo/menu");
        loading_back = Game.Content.Load<Texture2D>("todo/idle");
        loading_icon = Game.Content.Load<Texture2D>("Definitivo/downloading");
        page_flip = Game.Content.Load<SoundEffect>("Sound/page_flip");

        font_button = Game.Content.Load<SpriteFont>("Fonts/menu_piccolo");

      input_manager.OnHorizontalFlick += new InputManager.Flick(OnFlick);

        //PROVA
      //input_manager.OnVerticalDrag += new InputManager.Drag(OnDrag);
      //input_manager.OnDragCompleted += new InputManager.DragCompleted(OnDragCompleted);

      menu_button = new BoxedLabelButton(sprite_batch, menu, new Vector2(644, 420), font_button, Lang.UI_Menu, Color.White, false, currentState.options);
      menu_button.OnPress += new Press((me) =>
          {
              Game.Components.Add(new MenuReadPopup(Game, this));
              Game.TargetElapsedTime = TimeSpan.FromSeconds(1 / 30.0f);
          });
      entries.Add(menu_button);



      //if(Game.Window.CurrentOrientation==DisplayOrientation.Portrait)
      //{

      //}


      pages = pages_landscape;
      current_page = findPage(currentState.currentBook.currentWord);
      if (!prev_book_path.Equals(book_path) || !fontident.Equals(prev_font) )
      {
          loading = true;
          
          //words = GetEbook(book_path).Replace("\r\n\r\n", "\n\n ").Replace("\r\n", "\n ").Split(new[] { ' ' }).ToList();
          pages_landscape.Clear();
          pages_portrait.Clear();
          pages.Clear();
          new Thread(() =>
            {
                StringBuilder sb = new StringBuilder(80);                
                words = GetEbook(book_path).Replace("\r\n\r\n", "\n\n ").Replace("\r\n", "\n ")
                    .ToString().Split(new[] { ' ' }).ToList();
                bool waitme = true;
                new Thread(() =>
                  {
                      automaticGetCurrentBookPages(bookbody_rectangle, pages_landscape);
                      waitme = false;
                      
                  }).Start();
                var port_rect = new Rectangle(bookbody_rectangle.X, bookbody_rectangle.Y, bookbody_rectangle.Height, bookbody_rectangle.Width);
                automaticGetCurrentBookPages(port_rect, pages_portrait);
                while (waitme) Thread.Sleep(100);
                loading = false;
                prev_book_path = book_path;
                prev_font = fontident;
            }).Start();
          current_page = findPage(currentState.currentBook.currentWord);
      }

      //Window_OrientationChanged(null, null);
      //(Game as EbookReader).graphics.ApplyChanges();
 
      base.LoadContent();
    }


    bool loading = false;
    bool exited = false;
    protected override void Dispose(bool disposing)
    {
        exited = true;
        if (currentState.currentBook!=null)
            currentState.currentBook.currentWord = pages[current_page].firstWord;
        //currentState.currentBook = null;
        currentState.SaveState();

        input_manager.OnHorizontalFlick -= new InputManager.Flick(OnFlick);
        //input_manager.OnVerticalDrag -= new InputManager.Drag(OnDrag);
        //input_manager.OnDragCompleted -= new InputManager.DragCompleted(OnDragCompleted);

        Game.Components.Remove((IGameComponent)input_manager);
        //for (int i = 0; i < Game.Components.Count; i++)
        //    if (Game.Components[i] is InputManager)
                //(Game.Components[i] as InputManager).Active = true;

        //graphics.SetLandscapeRightOrientation();
        (Game as EbookReader).graphics.SetLandscapeLeftOrientation();
        Game.Window.OrientationChanged -= new EventHandler<EventArgs>(Window_OrientationChanged);
        disposed = true;
        base.Dispose(disposing);
    }
    bool disposed = false;
    float timeToStart = 0;

    float last_f;
    int prev_page;

    float toComponentstart = 0;
    bool initialPopupShowed = false;
    public override void Update(GameTime gameTime)
    {
        toComponentstart += (float)gameTime.ElapsedGameTime.TotalSeconds;

        if (toComponentstart > 0.5 && !initialPopupShowed)
        {
            if (!EbookReader.state.hints[3])
            {
                Game.Components.Add(new LargeMessagePopup(Game, Lang.Tip, Lang.TIP4));
                EbookReader.state.hints[3] = true;
            }
            else if(EbookReader.isTrial)
            {
                Game.Components.Add(new TrialPopup(Game));
            }
            initialPopupShowed = true;
        }

        if (toComponentstart > 0.8f)
        {
            if (!disposed && input_manager.Active && (Game as EbookReader).graphics.SupportedOrientations == DisplayOrientation.LandscapeLeft)
            {
                (Game as EbookReader).graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft | DisplayOrientation.Portrait;
                (Game as EbookReader).graphics.ApplyChanges();
                Window_OrientationChanged(null, null);
            }
            else if (!disposed && !input_manager.Active && (Game as EbookReader).graphics.SupportedOrientations == (DisplayOrientation.LandscapeLeft | DisplayOrientation.Portrait))
            {
                (Game as EbookReader).graphics.SupportedOrientations = DisplayOrientation.LandscapeLeft;
                (Game as EbookReader).graphics.ApplyChanges();
                Window_OrientationChanged(null, null);
            }
        }
        else
        {
            timeToStart += (float)gameTime.ElapsedGameTime.TotalSeconds;
        }


        if (current_page != prev_page)
        {
            if (currentState.options.audio)
                page_flip.Play();
        }
        prev_page = current_page;
        if (loading)
            timetoload += (float)gameTime.ElapsedGameTime.TotalSeconds;
        enabledInput = !loading;
        var stopped = false;
        if (Math.Abs(forceX) > Math.Abs(forceY))
            forceY = 0;
        position.Y += forceY * (Game.Window.CurrentOrientation == DisplayOrientation.LandscapeLeft ? 3f : 5f);
       
            if (forceY > 0)
            {
                int i = 0;
            }
            if (Math.Abs(forceY) >= 1f)
                forceY = MathHelper.Lerp(forceY, 0.0f, Math.Min((float)gameTime.ElapsedGameTime.TotalSeconds * (float)Math.Min(200 / Math.Abs(forceY), 6f), 0.5f));
            else
            {
                forceY = 0.0f;               
            }

        if (!(dragging || loading))
            {

            if (forceY <= 0.1f)
            {
                stopped = true;
            }
            if (Vector2.Distance(position, new Vector2(MARGIN, MARGIN)) > 1f)
            {
                position = Vector2.Lerp(position, new Vector2(MARGIN, MARGIN), Math.Min(1, (float)gameTime.ElapsedGameTime.TotalSeconds * 2 * 240 
                    / Vector2.Distance(position, new Vector2(MARGIN, MARGIN))));
                stopped = stopped && false;
            }
            else
            {
                position = new Vector2(MARGIN, MARGIN);
                stopped = stopped && true; ;
                //if (stopped) Game.TargetElapsedTime = TimeSpan.FromSeconds(0.2);
            }
            //}
            //else
            //{
        }


        if (!stopped)
        {
            menu_button.box_position = Vector2.SmoothStep(menu_button.box_position, new Vector2(800, 420), 10 * (float)Math.Min(gameTime.ElapsedGameTime.TotalSeconds, 0.05f));
        }
        else
        {
            if (Vector2.Distance(menu_button.box_position, new Vector2(644, 420)) < 0.1f && toComponentstart > 2)
                Game.TargetElapsedTime = TimeSpan.FromSeconds(1 / 15.0f);
            else
                menu_button.box_position = Vector2.SmoothStep(menu_button.box_position, new Vector2(644, 420), 10 * (float)Math.Min(gameTime.ElapsedGameTime.TotalSeconds, 0.05f));

        }
        


        if (position.Y < -GraphicsDevice.Viewport.Height / 2)
                if (current_page >= pages.Count-1)
                    position = new Vector2(MARGIN, GraphicsDevice.Viewport.Height / 2);
                else
                {
                    current_page++;
                    position = position + new Vector2(0, GraphicsDevice.Viewport.Height);
                }
        else if (position.Y > GraphicsDevice.Viewport.Height / 2)
                if (current_page < 1)
                    position = new Vector2(MARGIN, GraphicsDevice.Viewport.Height / 2);
                else
                {
                    current_page--;
                    position = position - new Vector2(0, GraphicsDevice.Viewport.Height);
                }

            //if (GamePad.GetState(PlayerIndex.One).IsButtonDown(Buttons.Back))
            //    ScreenManager.SelectMainMenu(Game);
        
        base.Update(gameTime);
    }


    Rectangle bookbody_rectangle = new Rectangle(22, 18, 768, 406);
    public override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(bgColor);
      sprite_batch.Begin();
      sprite_batch.Draw(background, GraphicsDevice.Viewport.Bounds, Color.White);

      var body = 
          (Game.Window.CurrentOrientation == DisplayOrientation.LandscapeLeft || ((EbookReader)Game).graphics.SupportedOrientations==DisplayOrientation.LandscapeLeft)
          ? new Rectangle(12, 13, 778, 426) : new Rectangle(8, 10,  458, 755);
      if (current_page >= pages.Count)
      {
          sprite_batch.Draw(bookbody,body, Color.White);
          var dots = ".";
          for (int i = 0; i < gameTime.TotalGameTime.Seconds % 3; i++)
          {
              dots += ".";
          }
          sprite_batch.DrawString(font, "Loading" + dots, new Vector2(50, 50), Color.CornflowerBlue);
      }
      else
      {
          var str_off = font.MeasureString("" + current_page).Y;
          var str_off_x = font.MeasureString("" + current_page).X;
          var num_position = Game.Window.CurrentOrientation == DisplayOrientation.LandscapeLeft ? new Vector2(22, 435 - str_off) : new Vector2(450-str_off_x, 750-str_off);
          if (current_page > 0)
          {
              sprite_batch.Draw(bookbody, new Rectangle(body.X + (int)position.X, body.Y + (int)position.Y - (int)GraphicsDevice.Viewport.Height,body.Width, body.Height), Color.White);
              sprite_batch.DrawString(font, pages[current_page - 1].text, new Vector2(22, 18) + position - new Vector2(0, GraphicsDevice.Viewport.Height), textColor * 0.5f, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
              sprite_batch.DrawString(font, "" + (current_page), num_position + position - new Vector2(0, GraphicsDevice.Viewport.Height), textColor * 0.5f, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
          }
          //sprite_batch.DrawString(font, pages[current_page], position, Color.CornflowerBlue);
          sprite_batch.Draw(bookbody, new Rectangle(body.X + (int)position.X, body.Y + (int)position.Y, body.Width, body.Height), Color.White);
          sprite_batch.DrawString(font, pages[current_page].text, new Vector2(22, 18) + position, textColor);
          sprite_batch.DrawString(font, "" + (current_page + 1), num_position + position, textColor * 0.8f, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
          
          if (current_page < pages.Count - 1)
          {
              sprite_batch.Draw(bookbody, new Rectangle(body.X + (int)position.X, body.Y + (int)position.Y + (int)GraphicsDevice.Viewport.Height, body.Width, body.Height), Color.White);
              sprite_batch.DrawString(font, pages[current_page+1].text, new Vector2(22, 18) + position + new Vector2(0, GraphicsDevice.Viewport.Height), textColor);
              sprite_batch.DrawString(font, "" + (current_page + 1), num_position + position + new Vector2(0, GraphicsDevice.Viewport.Height), textColor * 0.8f, 0, Vector2.Zero, scale, SpriteEffects.None, 1);
     
          }

      }



      //sprite_batch.DrawString(font, "" + timetoload+"\n"+pages.Count, Vector2.UnitY * 200, Color.Red);
      sprite_batch.End();

      base.Draw(gameTime);
      if (loading)
      {
          sprite_batch.Begin();
          var rect = new Rectangle(400, 240, 50, 50);
          sprite_batch.Draw(loading_back,GraphicsDevice.Viewport.Bounds, Color.White);
          sprite_batch.Draw(loading_icon, new Vector2(GraphicsDevice.Viewport.Bounds.Center.X,GraphicsDevice.Viewport.Bounds.Center.Y), null, Color.White, (float)gameTime.TotalGameTime.TotalSeconds, new Vector2(loading_icon.Width / 2, loading_icon.Height / 2), 1f,  SpriteEffects.None, 0.0f);
          sprite_batch.End();
      }

    }

    int clamp(int min, int max, int i)
    {
        if (i < min) return min;
        if (i > max) return max;
        return i;
    }





    #region Generate Pages

    #region Commented Code

    //IEnumerable<string> FindPages()
    //{
    //  int i = 0;
    //  int count = 0;
    //  string current_page = "";
    //  while (i + count < words.Count)
    //  {
    //    var next_page = current_page + words[i + count] + " ";
    //    var page_size = scale*font.MeasureString(next_page);
    //    if (page_size.X > GraphicsDevice.Viewport.Width - 2 * MARGIN)
    //    {
    //      next_page = current_page + "\n" + words[i + count] + " ";
    //      page_size = scale*font.MeasureString(next_page);
    //    }
    //    if (page_size.Y < GraphicsDevice.Viewport.Height - 2 * MARGIN)
    //    {
    //      current_page = next_page;
    //      count++;
    //    }
    //    else
    //    {
    //      i = i + count;
    //      count = 0;
    //      yield return current_page;
    //      current_page = "";
    //    }
    //  }
    //  yield return current_page;
    //}

    #endregion


      
    //IEnumerable<Page> GetCurrentBookPages()
    //{
    //    int save_screen_width = bookbody_position.Width - 2 * MARGIN;
    //    string row = "";
        
    //    int count = 0, row_in_current_page = 0;
    //    int max_rows = (int)((bookbody_position.Height - 2 * MARGIN) / (scale*font.MeasureString("B").Y));

    //    Page current_page = new Page() { firstWord = count, text = new System.Text.StringBuilder(80) };

    //    while (count < words.Count)
    //    {
    //        var word = words[count];
    //        for (int j = 0; j < word.Length; j++)
    //        {
    //            var c = word[j];
    //            if (c != '\n' && !font.Characters.Contains(c))
    //            {
    //                word = word.Replace(c, '?');
    //            };
    //        }            

    //        if (scale*font.MeasureString(word).X > save_screen_width)
    //        {
                
    //            var i = word.Length - 1;
    //            while (scale*font.MeasureString(word.Substring(0, i)).X > save_screen_width)
    //                i--;
    //            words.Insert(count + 1, word.Substring(i + 1));
    //            words[count] = word.Substring(0, i);
    //            word = word.Substring(0, i);
    //        }

    //        var tmp_row = row + word;
    //        var row_width = scale*font.MeasureString(tmp_row).X;
    //        if (row_width <= save_screen_width)
    //        {
    //            if (words[count].Contains(".\n") || words[count].Contains(".\"\n") || words[count].Contains("\n\n"))
    //            {
    //                current_page.text += row + word;
    //                if (words[count].Contains("\n\n"))
    //                    row_in_current_page += 2;
    //                else
    //                    row_in_current_page++;
    //                row = "";
    //            }
    //            else
    //                row += (words[count].Contains("\n") ? word.Remove(words[count].Length - 1) : word) + " ";

    //            count++;
    //        }
    //        else
    //        {
    //            current_page.text += row.Trim() + "\n";
    //            row_in_current_page++;
    //            row = "";
                
    //        }

    //        if (row_in_current_page >= max_rows)
    //        {
    //            current_page.numWords = count - current_page.firstWord;
    //            yield return current_page;
    //            //rows.Add(current_page);
    //            current_page = new Page() { firstWord = count, text = "" };
    //            row = "";
    //            row_in_current_page = 0;
    //        }
    //    }

    //    //rows.Add(current_page);
    //    yield return current_page;

    //    //return rows;
    //}


    String newline = "\n", newline2 = "\n\n", dotnewline = ".\n", dotquotenewline = ".\"\n", space = " ", empty = "";
    void automaticGetCurrentBookPages(Rectangle bookbody_rectangle, List<Page> pages)
    {
        StringBuilder tmp_row = new StringBuilder(80);
        int save_screen_width = bookbody_rectangle.Width - 2 * MARGIN;
        System.Text.StringBuilder row = new  System.Text.StringBuilder(80);

        int count = 0, row_in_current_page = 0;
        int max_rows = (int)((bookbody_rectangle.Height - 2 * MARGIN) / (font.MeasureString("B").Y));

        Page current_page = new Page() { firstWord = count, text = new System.Text.StringBuilder(80) };


        int current_str_lenght = 0;

        while (count < words.Count)
        {
            var word = words[count];
            //for (int j = 0; j < word.Length; j++)
            //{
            //    var c = word[j];
            //    if (c != '\n' && !font.Characters.Contains(c))
            //    {
            //        word = word.Replace(c, '?');
            //    };
            //}

            if (font.MeasureString(word).X > save_screen_width)
            {

                var i = word.Length - 1;
                while (font.MeasureString(word.Substring(0, i)).X > save_screen_width)
                    i--;
                words.Insert(count + 1, word.Substring(i + 1));
                word = word.Substring(0, i);
                words[count] = word;
               
            }

            
           
            tmp_row.Remove(0, tmp_row.Length);
            tmp_row.Append(row).Append(word);
            var row_width = font.MeasureString(tmp_row).X;
            
            if (row_width <= save_screen_width)
            {
                current_str_lenght += word.Length;
                var next_string_length = current_str_lenght + (count < words.Count-1 ? words[count+1].Length : 0);

                if (words[count].Contains(dotnewline) || words[count].Contains(dotquotenewline) || words[count].Contains(newline2)
                    || (next_string_length < 70 && words[count].Contains(newline)))
                {
                    current_page.text.Append(row);
                    current_page.text.Append(word);
                    if (words[count].Contains(newline2))
                        row_in_current_page++;
                    row_in_current_page++;
                    row.Remove(0, row.Length);
                    current_str_lenght = 0;
                }
                else
                {
                    if (words[count].Contains(newline))
                        current_str_lenght = 0;
                    row.Append((words[count].Contains(newline) ? word.Remove(words[count].Length - 1) : word));
                    row.Append(space);
                    current_str_lenght++;
                }

                count++;
            }
            else
            {
                current_page.text.AppendLine(row.ToString().Trim());
                //+newline;
                row_in_current_page++;
                row = row.Remove(0,row.Length);

            }

            current_page.numWords = count - current_page.firstWord;
            if (row_in_current_page >= max_rows)
            {
                //current_page.numWords = count - current_page.firstWord;
                //yield return current_page;
                pages.Add(current_page);
                //rows.Add(current_page);
                current_page = new Page() { firstWord = count, text = new System.Text.StringBuilder(80) };
                row = row.Remove(0, row.Length);
                row_in_current_page = 0;

                if (count > currentState.currentBook.currentWord+200)
                {
                    if(page_not_loaded)
                        this.current_page = findPage(currentState.currentBook.currentWord);
                    Thread.Sleep(10);
                    loading = false;
                }
                if (exited)
                    return;

            }
        }

        //rows.Add(current_page);
        pages.Add(current_page);
        prev_book_path = book_path;
        prev_font = fontident;

        if (page_not_loaded)
            this.current_page = findPage(currentState.currentBook.currentWord);
        //yield return current_page;
        //Thread.Sleep(5);
        //return rows;
    }

    #endregion

//    #region Save & Restore State

//    void RestoreState()
//    {
//#if WINDOWS_PHONE
//        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
//        IsolatedStorageFileStream stream;
//        try
//        {
//            stream = store.OpenFile("reader_state.txt", FileMode.Open, FileAccess.ReadWrite);
//        }
//        catch (Exception)
//        {
//            store.Dispose();
//            return;
//        }
//#else
//            FileStream stream = File.Open(FileName, FileMode.Create);			
//#endif

//        XmlSerializer serializer = new XmlSerializer(typeof(ReaderState));
//        var state = serializer.Deserialize(stream) as ReaderState;
//        current_page = state.CurrentPage;

//        stream.Close();

//#if WINDOWS_PHONE
//        store.Dispose();
//#endif
//    }

//    void SaveState(object sender, EventArgs e)
//    {
//#if WINDOWS_PHONE
//        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
//        IsolatedStorageFileStream stream = store.OpenFile("reader_state.txt", FileMode.Create, FileAccess.ReadWrite);
//#else
//            FileStream stream = File.Open(FileName, FileMode.Create);			
//#endif

//        XmlSerializer serializer = new XmlSerializer(typeof(ReaderState));
//        serializer.Serialize(stream, new ReaderState()
//        {
//            CurrentPage = current_page
//        });

//        stream.Close();

//#if WINDOWS_PHONE
//        store.Dispose();
//#endif
//    }

//    #endregion

    StringBuilder GetEbook(string path)
    {
        //StreamReader sr = new StreamReader(TitleContainer.OpenStream(path));
        IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
        IsolatedStorageFileStream stream;
        try
        {
            stream = store.OpenFile(path, FileMode.Open, FileAccess.ReadWrite);
        }
        catch (Exception)
        {
            store.Dispose();
            return new StringBuilder(80);
        }
        var sr = new StreamReader(stream);

        return new StringBuilder(sr.ReadToEnd());
    }

    void OnFlick(float delta)
    {
        if (Math.Abs(delta)<500 || forceY>5)
            return;
        if (delta > 0.0f)
            current_page--;
        else
            current_page++;

        current_page = clamp(0, pages.Count - 1, current_page);
    }

    bool page_not_loaded = true;
    public int findPage(int word)
    {
#warning algoritmo + efficiente
        for (int i = 0; i < pages.Count; i++)
        {
            var page = pages[i];
            if (word >= page.firstWord && word < page.firstWord + page.numWords)
            {
                page_not_loaded = false;
                return i;
            }
        }
        page_not_loaded = true;
        return 0; 
    }
  }
}
